<template>
  <div>
    <div><el-button type="default" @click="$router.push('/ContainerManage')">返回镜像管理</el-button></div>
    <h2>容器 {{ containerId }} 日志</h2>
    <pre style="background:#000;color:#0f0;padding:10px;height:400px;overflow:auto;">
      {{ logs }}
    </pre>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, onDeactivated } from 'vue';
import { useRoute } from 'vue-router';

const route = useRoute();
const containerId = route.params.id;
const logs = ref('');
let socket: WebSocket | null = null;

onMounted(() => {
  if (socket && socket.readyState === WebSocket.OPEN) {
      socket.close();
      console.log('onMounted: WebSocket处于打开状态先关闭');
    }
  socket = new WebSocket(`ws://localhost:8000/docker/ws/containers/${containerId}/logs`);
  socket.onmessage = (event) => {
    logs.value += event.data + '\n';
  };
});


onBeforeUnmount(() => {
  console.log("onBeforeUnmount event start.");
  closeSocket()
  console.log("onBeforeUnmount event finished.");
});
onDeactivated(() =>{
  console.log("onDeactivated event start. ")
  closeSocket()
  console.log("onDeactivated event finished. ")
});

function closeSocket() {
  if (socket && socket.readyState === WebSocket.OPEN) {
    socket.close();
    console.log('WebSocket 已关闭');
  }
}

</script>